package com.czy.owner.api;

import android.text.TextUtils;

import com.czy.owner.net.api.BaseApi;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.http.Part;
import rx.Observable;

/**
 * Created by hep on 2018/1/17
 */

public class UploadFrameNumberApi extends BaseApi {
    private String session;
    private String path;


    public UploadFrameNumberApi(HttpOnNextListener listener, RxAppCompatActivity rxAppCompatActivity) {
        super(listener, rxAppCompatActivity);
        setShowProgress(true);
        setCache(false);
        setCookieNetWorkTime(0);//有网缓存0s,在0s内点击无效


    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getSession() {
        return session;
    }

    public void setSession(String session) {
        this.session = session;
    }


    @Override
    public Observable getObservable(Retrofit retrofit) {
        HttpPostService service = retrofit.create(HttpPostService.class);
        HashMap<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(getSession())) {
            map.put("session", getSession());
        }
        List<MultipartBody.Part> partList = new ArrayList<>();
        if (!TextUtils.isEmpty(path)) {
//            params.addBodyParameter("file" + (i + 1), new FileInputStream(new File(picList.get(i))), "img/jpg", "pic" + i + ".jpg");
            List<File> fileList = new ArrayList<>();
            fileList.add(new File(path));
            partList = filesToMultipartBodyParts(fileList);
        }
        return service.getVinInfo(map, partList);
    }

    private List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("multipartFiles", file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }
}

